-- UIBuyCostume
-- Create by zouyb
-- 购买时装

-- 模型缩放比例
local HERO_MODEL_SCALE = 0.6

--UIBuyCostume继承自Layer
UIBuyCostume = class("UIBuyCostume", function()
    return cc.Layer:create();
end);

function UIBuyCostume.create(heroId, itemId, openType)
    return UIBuyCostume.new(heroId, itemId, openType);
end

local resize;

--构造函数
function UIBuyCostume:ctor(heroId, itemId, openType)
    self:setName("UIBuyCostume");
    self.itemId = itemId;
    self.heroId = heroId;
    self.openType = openType;

    --初始化
    local node = cc.CSLoader:createNode("layout/hero/BuyCostume.csb");
    self:addChild(node);
    self.node = node;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件回调
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    resize(self);
end

-- 注册点击事件
function UIBuyCostume:registerTouchEvent()
   -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIBuyCostume");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType == "activity" then
                self:tryBuyActivity();
            else
                local buyPrice = ItemM.query(self.itemId, "buy_price")[1][3];
                if ME.user.dbase:query("gem") < buyPrice then
                    showGemLackConfirm();
                    return;
                end

                -- 购买时装
                Operation.cmd_buy_costume(self.itemId);
            end
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    if self.openType == "activity" then
        btnBuy:setTitleText(getLocStr("btn_text_exhcange"));
    else
        btnBuy:setTitleText(getLocStr("btn_text_buy"));
    end
end

-- 尝试购买
function UIBuyCostume:tryBuyActivity()
    local activityId = EquipM.query(self.itemId, "dbase")["activity_id"];
    local goodsId = EquipM.query(self.itemId, "dbase")["exchange_id"];

    -- 判断能否购买
    local ret = ActivityM.canExchange(activityId, goodsId, 1);

    if ret ~= true then
        AudioM.playFx("market_buy_failed");
        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_exchange_over"));
        elseif type(ret) == "string" and string.endWith(ret, "_lack") then
            -- 属性不足
            local field = string.sub(ret, 1, -6);
            if field == "gem" then
                showGemLackConfirm();
            else
                local fieldName;
                if string.startWith(field, "item_") then
                    local classId = tonumber(string.sub(field, 6, -1));
                    fieldName = ItemM.query(classId, "name");
                else
                    fieldName = FieldsM.getFieldName(field);
                end

                local msg = string.format(getLocStr("fail_to_do_operate2"), fieldName, getLocStr("exchange"));
                alert(msg);
            end
        end
        -- 关闭当前界面
        -- UIMgr.getCurrentScene():removeFormByName("UIBuyCostume");
        return;
    end

    -- 执行购买
    AudioM.playFx("market_buy_success");
    Operation.cmd_activity_exchange(activityId, goodsId, 1);
end

-- 注册事件回调
function UIBuyCostume:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIBuyCostume", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIBuyCostume" then
            if self.openType == "activity" then
                local uiTopMenu = UIMgr:getCurrentScene().topMenu;
                local price = ItemM.query(self.itemId, "buy_price");
                uiTopMenu:setExchangeCurrency(price[1][2]);
                uiTopMenu:show(TOPMENU_FRAME_ACTIVITY_EXCHANGE, TOPMENU_FRAME_GEM);
            else
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            end
        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enter" then
            local uiHeroInfo = UIMgr.getCurrentScene():getFormByName("UIHeroInfo");
            if uiHeroInfo then
                self.oldVisible = uiHeroInfo:isVisible();
                uiHeroInfo:setVisible(false);
            end
        elseif ev == "exit" then
            EventMgr.removeAll("UIBuyCostume");
            cclog("UIBuyCostume 界面析构清理");

            local uiHeroInfo = UIMgr.getCurrentScene():getFormByName("UIHeroInfo");
            if uiHeroInfo then
                uiHeroInfo:setVisible(self.oldVisible);
                FormEffectM.runAppearEffect(uiHeroInfo);
            end
        end
    end);
end

-- 重绘
function UIBuyCostume:redraw()
    -- 标题
    local name = ItemM.query(self.itemId, "name");
    local titleLabel = findChildByName(self.node, "CT/bg/title");
    titleLabel:setString(name);
    TextStyleM.setTitleStyle(titleLabel);

    -- 道具描述
    local buyPrice = ItemM.query(self.itemId, "buy_price");
    local itemDesc = string.format(ItemM.query(self.itemId, "desc"), buyPrice[1][3]);
    local descLabel = findChildByName(self.node, "CT/item_desc");
    TextStyleM.setTextStyle(descLabel,TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, itemDesc);

    -- 属性描述
    local propDesc = ItemM.query(self.itemId, "detail");
    local propLabel = findChildByName(self.node, "CT/prop_desc");
    TextStyleM.setTextStyle(propLabel,TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
    applyString(propLabel, propDesc);

    -- 背景图
    local heroBg = findChildByName(self.node, "CT/hero_bg");
    heroBg:setOpacity(128);

    -- 显示英雄模型
    self:createHeroModel();
end

-- 创建英雄模型
function UIBuyCostume:createHeroModel()
    local headImg = findChildByName(self.node, "CT/hero_node/hero_head");
    local modelNode = findChildByName(self.node, "CT/hero_node/model_node");
    local click = findChildByName(self.node, "CT/click");

    -- 获取英雄模型
    local modelId = EquipM.queryPetModelID(self.itemId);
    local icon = PetM.queryModel(modelId, "large_icon");
    local iconPath = getHeroLargeIconPath(icon);

    local animation = PetM.queryModel(modelId, "animation");
    if animation == "" or onlyImage == true then
        -- 未配置动画，或者仅显示图片，默认显示头像
        headImg:setVisible(true);
        headImg:loadTexture(iconPath);
    else
        -- 显示模型动画
        headImg:setVisible(false);

        local animName = PetM.queryModel(modelId, "animation");
        if animName ~= nil then
            local animaNode = HeroDisplay.create(modelId);
            animaNode:setScale(HERO_MODEL_SCALE);

            -- 播放动作
            local index = 0;
            local function onClick(sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    local actions = { HERO_ACTION_DAMAGED, HERO_ACTION_ATTACK,
                                      HERO_ACTION_CAST_ME, HERO_ACTION_CAST_OTHER };

                    index = (index % #actions) + 1;
                    animaNode:switchAction(actions[index]);
                end
            end

            click:addTouchEventListener(onClick);

            modelNode:removeAllChildren();
            modelNode:addChild(animaNode);
        end
    end
end

resize = function(self)
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


